<template>
  <div class="app-container">
    <div class="block">
      <el-form class="query-wrapper" :model="queryParams">
        &nbsp;&nbsp;
        <el-select
          v-model="queryParams.voyageId"
          filterable
          placeholder="choose voyage"
        >
          <el-option
            :key="item.voyageId"
            :label="item.vesselName + item.voyageNo"
            :value="item.voyageId"
            v-for="item in voyages"
          >
          </el-option>
        </el-select>
        &nbsp;&nbsp;
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
        <el-button type="primary" icon="search"  @click="search">{{
          $t("ship.button.search")
        }}</el-button>
        &nbsp;&nbsp;
        <el-button type="primary" :disabled="listData.length == 0" @click="handleSubmit">
            {{ $t("ship.button.submit") }}
          </el-button>  
      </el-form> 
    </div>
  </div>

  <!-- <div class="table-boxs" style="margin: 50px 0 0 0">
    <div class="table-box"> -->
      <el-table
        ref="tableRef"
        stripe
        :data="listData"
        style="width: 100%"
        :border="true"
        :cell-style="{textAlign:'center'}"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="bookingNo" label="Booking No" width="120" />
        <el-table-column prop="channel" label="Booking Channel" width="200"/>
        <el-table-column prop="terminal" :label="'Terminal Ground' +'\r\n' + 'Service Provider'" width="200"/>
        <el-table-column prop="payer" label="Party to pay freight"  width="200"/> 
        <el-table-column prop="totalFreight" label="Total Freight"  width="120"/>  
        <el-table-column prop="shipper" label="Shipper" />
        <el-table-column prop="notifyParty" label=" Notify Party" width="150"/>
        <el-table-column prop="pol" label="POL" />
        <el-table-column prop="pod" label="POD" />
        <el-table-column prop="freightRate" label="Feight rate"  width="170"/>
        <el-table-column prop="freightRate" label="Feight rate"  width="170"/>
        <el-table-column prop="brand" label="Brand" />
        <el-table-column prop="model" label="Model" />
        <el-table-column
          prop="cargoDesc"
          label="Cargo Description"
          width="200"
        />
        <el-table-column label="Operation" width="120" fixed="right">
          <template #default="scope">
            <span class="btn-primary" @click="editClickEvent(scope.row)">{{
              $t("ship.button.edit")
            }}</span
            >&nbsp;&nbsp;
            <span class="btn-primary" @click="removeClickEvent(scope.row.id)">{{
              $t("ship.button.remove")
            }}</span>
          </template>
        </el-table-column>
      </el-table>
    <!-- </div>
  </div> -->

  <el-dialog
    class="add_dialog"
    destroy-on-close
    draggable
    :title="dialogTitle"
    v-model="dialogFormVisible"
  >
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="Booking channel"
            label-width="120px"
            prop="channel"
            required
          >
            <el-input v-model="formParam.channel" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="Terminal Ground Service Provider"
            label-width="170px"
            prop="channel"
            required
          >
            <el-input v-model="formParam.terminal" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="Party to pay freight"
            label-width="170px"
            prop="payer"
            required
          >
            <el-input v-model="formParam.payer" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="Measure Type" label-width="120px" required>
            <el-select v-model="formParam.measureType" @change="handleCbmType">
              <el-option
                :key="index"
                :label="item"
                :value="index"
                v-for="(item, index) in cbmTypes"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Rate Type" label-width="120px" required>
            <el-select v-model="formParam.rateType" @change="setRateType">
              <el-option
                :key="index"
                :label="item"
                :value="index"
                v-for="(item, index) in rateTypes"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="Freight Rate" label-width="120px">
            <el-input-number v-model="formParam.freightRate" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Total Freight" label-width="120px" required>
            {{ formParam.totalFreight }} {{ formParam.measureType }}
            {{ formParam.rateType }}
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item
            label="Length(m)"
            label-width="120px"
            prop="unitLength"
            required
          >
            <el-input-number v-model="formParam.unitLength" :precsion="3" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="Width(m)"
            label-width="120px"
            prop="unitWidth"
            required
          >
            <el-input-number v-model="formParam.unitWidth" :precsion="3" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="Height(m)"
            label-width="120px"
            prop="unitHeight"
            required
          >
            <el-input-number v-model="formParam.unitHeight" :precsion="3" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="unit cbm" label-width="120px">
            <template>
              {{
                (
                  formParam.unitLength *
                  formParam.unitHeight *
                  formParam.unitWidth
                ).toFixed(3)
              }}
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="unit weight (kg)"
            label-width="120px"
            prop="unitWeight"
            required
          >
            <el-input type="number" v-model="formParam.unitWeight" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="total units"
            label-width="120px"
            prop="totalUnits"
            required
          >
            <el-input-number v-model="formParam.totalUnits" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="total volume（cbm）" label-width="200px">
            <template>
              {{
                (
                  formParam.unitLength *
                  formParam.unitHeight *
                  formParam.unitWidth *
                  formParam.totalUnits
                ).toFixed(2)
              }}
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="Total Weight (kg)"
            label-width="200px"
            prop="totalWeight"
            required
          >
            <template>
              {{
                (
                  (formParam.totalUnits || 0) * (formParam.unitWeight || 0)
                ).toFixed(2)
              }}
            </template>
            <!-- <el-input-number v-model="formParam.totalWeight" disabled /> -->
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="B/L NO. 提单号" label-width="120px" prop="totalVolume">
            <el-input type="number" v-model="formParam.spareVolume" disabled />
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="Remarks" label-width="120px" prop="remark">
            <el-input v-model="formParam.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
        }}</el-button>
        <el-button @click="resetForm" type="warning">{{
          $t("ship.button.reset")
        }}</el-button>
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
// @ts-nocheck
import { ref, onMounted, reactive, watch } from "vue";
import service from "@/utils/request";
import { ElNotification, ElMessageBox } from "element-plus";
import { useTableDrag } from '@/hooks/useHooks';

const { tableRef, proxy } = useTableDrag();

const custForm = ref();
const dialogTitle = ref("");
const initForm = {
  id: null,
  model: null,
  freightRate: null,
  totalFreight: null,
  totalUnits: null,
  unitHeight: null,
  unitWeight: null,
  unitLength: null,
  unitWidth: null,
  unitCbm: null,
  channel: null,
  terminal: null,
  payer: null,
  remark: null,
  measureType: null,
  rateType: null,
};

const formParam = reactive(Object.assign({}, initForm));

const total = ref(0);

const rules = ref({
  companyId: [{ required: true, message: "carrier can't be blank" }],
});

const cbmTypes = ["unfreighted", "measured"];
const rateTypes = ["Simple Rate", "High Level Rate"];

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  status: 2,
  companyId: null,
  voyageId: null,
  orderByColumn: undefined,
  isAsc: undefined,
});

let carriers = ref([] as any);
let vessels = ref([] as any);
let voyages = ref([] as any);
let ports = ref([] as any);
let recordData = ref([] as any);
const listData = ref([]);
const refreshTable = async () => {
  let result = await service.get("/shipping/freighted/getTable", {
    params: queryParams,
  });
  listData.value = result.data;

  total.value = result.total;
};
const resetQuery = (data) => {
    Object.assign(queryParams, data)
    listData.value = []
}
const dialogFormVisible = ref(false);

const dialogFormVisible1 = ref(false);
const editClickEvent = (row: any) => {
  dialogTitle.value = "Update Freighted";
  dialogFormVisible.value = true;
  Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
  isAdd = false;
};

let isAdd = false;

const addClickEvent = () => {
  dialogTitle.value = "Add booking";
  isAdd = true;
  dialogFormVisible1.value = true;
  Object.assign(formParam, initForm);
  recordData.value = [{ bookId: 10, channel: null }];
};

const handleCbmType = async (row) => {
  if (formParam.measureType == 1) {
    let params = { model: row.model };
    let result = await service.get("/shipping/vehicleModel/getInfo", params);
    if (result && result.data) {
      row.unitWeight = result.data.measureWeight;
      formParam.unitWidth = result.data.measureWidth;
      formParam.unitHeight = result.data.measureHeight;
      formParam.unitLength = result.data.measureLength;
    }
  }
};

const setRateType = async (row) => {
  if (formParam.rateType == 0) {
    formParam.totalFreight = (
      formParam.freightRate *
      formParam.totalUnits *
      formParam.unitHeight *
      formParam.unitHeight *
      formParam.unitLength
    ).toFixed(2);
  } else if (formParam.rateType == 1) {
    let value1:number = (
      formParam.freightRate *
      formParam.totalUnits *
      formParam.unitHeight *
      formParam.unitHeight *
      formParam.unitLength
    );
    let value2:number = (formParam.totalFreight =
      formParam.freightRate * formParam.totalUnits * formParam.unitWeight);

    formParam.totalFreight = value1 > value2 ?   value1.toFixed(2) : value2.toFixed(2);
  }
};

const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => {
  // @ts-ignore
  custForm.value.validate(async (valid) => {
    if (!valid) {
      // @ts-ignore
      ElNotification.warning({
        title: "Prompt information",
        message: "verification not success！",
        position: "bottom-right",
      });
      return;
    }

    await service[isAdd ? "post" : "put"]("shipping/freighted", formParam);
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right",
    });
    dialogFormVisible.value = false;
    search();
  });
};

const pageQuery = async (e) => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const search = async () => {
  let result = await service.get("/shipping/bookingFinal/getTable", {
    params: queryParams,
  });
  listData.value = result.data;
};


const uploadFile = async (event) => {
  if (event.target == null || event.target.files[0] == null) {
    return;
  }
  const formData = new FormData();
  formData.append("file", event.target.files[0]);
  await service["post"]("shipping/booking/uploadFile", formData);
};

const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};

const handleSubmit = ()=>{
  if (listData.value.length <= 0) {
    ElNotification.warning({
      title: "Prompt information",
      message: "no data to submit！",
      position: "bottom-right"
    });
    return;
  }

  ElMessageBox.confirm("Confirm to send the declare information to approve？", "Confirmation Information", {
    type: "warning"
  }).then(async () => {
    let params = { bookings: listData.value };
    await service.post(`shipping/freighted/submit`, params);
    ElNotification.success({
      title: "Prompt information",
      message: "submit the data success!",
      position: "bottom-right"
    });
    //await service.delete(`shipping/booking/${id}`);
  });
}

const removeClickEvent = (id) => {
  ElMessageBox.confirm(
    "Confirm to Remove the data？",
    "Confirmation Information",
    {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel",
    }
  ).then(async () => {
    await service.delete(`shipping/booking/${id}`);

    refreshTable();
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "Delete successfully!",
      position: "bottom-right",
    });
  });
};

let carrierCode = "";
let vesselCode = "";
let voyageNo = "";


onMounted(async () => {
  refreshTable();
});
</script>
<style lang="scss" scoped>
div.el-dialog {
  width: 1100px !important;
  max-width: 95vw;

  .el-select {
    width: 100%;
  }

  element.style {
    width: 3000;
  }

  .el-icon-upload {
    font-size: 2rem;
    cursor: pointer;
  }
}

.add_dialog {
  width: 1500px !important;
  max-width: 95vw;

  .el-select {
    width: 100%;
  }

  element.style {
    width: 4000;
  }

  .el-icon-upload {
    font-size: 2rem;
    cursor: pointer;
  }
}
.el-table__expand-column .cell {
  display: none;
}

.c-expand {
  color: #888;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  cursor: pointer;
  width: 100%;
  height: 100%;
}

.c-expand i {
  font-size: 16px;
}

.c-expand i.expand {
  font-size: 16px;
  transform: rotate(90deg);
  transition: all 0.25s;
}

.el-table thead .cell {
  white-space: pre-line !important;
}
.table-box1 {
  width: 4000px;
}
.table-boxs {
  width: 100%;
  overflow-x: auto;
}

.ipx {
  width: 100%;
  text-align: center;
}
 
</style>
